package cn.com.infohold.smartcity.jpush;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import library.utils.Logger;

/**
 * 线路呈现的服务
 */
public class JpushService extends Service {
    private static final String TAG = JpushService.class.getName();
    /**
     * 设置消息推送标签或设备别名
     */
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    private String userId;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        if (intent != null)
            userId = intent.getStringExtra("userId");
        Logger.debug("JPUSH USERID:" + userId);
        initPush();
    }


    public void initPush() {
        JPushInterface.resumePush(getApplicationContext());
        if (!TextUtils.isEmpty(userId)) {
            setAlias();
        }
        if (!TextUtils.isEmpty(userId)) {
            setTag();
        }
    }

    /**
     * 设置消息推送标签
     */
    public void setTag() {
        String tag = userId;
        Log.v(TAG, "=========tag:" + tag);
        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
//            Toast.makeText(PushRongService.this, "---error---", Toast.LENGTH_SHORT).show();
            return;
        }

        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!isValidTagAndAlias(sTagItme)) {
                //Toast.makeText(PushSetActivity.this,R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
            Log.v("main", "=========tag:" + sTagItme);
        }
//        tagSet.add(ScoGlobal.userData.getPhoneNumber());//手机号设置到Tag中
        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));
    }

    // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    /**
     * 设置消息推送Alias设备别名
     */
    public void setAlias() {
        String alias = userId;
        if (TextUtils.isEmpty(alias)) {
            //Toast.makeText(PushSetActivity.this,R.string.error_alias_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isValidTagAndAlias(alias)) {
            //Toast.makeText(PushSetActivity.this,R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        Log.v(TAG, "=========alias:" + alias);
        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
                case MSG_SET_TAGS:
                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    stop();
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
            }
            Log.v(TAG, "===mAliasCallback=====logs:" + logs);
        }

    };

    public boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    stop();
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
            }
            Log.v(TAG, "==mTagsCallback==========logs:" + logs);
        }

    };

    @Override
    public void onDestroy() {
        Log.i(TAG, "服务:onDestroy()");
//        JPushInterface.stopPush(getApplicationContext());
    }

    public void stop() {
        stopSelf();
    }
}
